<?php


namespace PKApp\DataBase\Classes;

use PKFrame\DataHandler\Arrays;
use PKFrame\Lib\DataBase;
use PKFrame\Service;

class DataBaseService extends Service
{

    public $count_rows = 0;

    public function __construct()
    {
        $this->moduleName = 'DataBase';
        parent::__construct();
    }

    protected function db(): DataBase
    {
        static $cls;
        !empty($cls) ?: $cls = new DataBase();
        if ($cls->is_install_DB) {
            /**
             * 执行安装向导的初始化存在的数据库名
             */
            $cls->SetDBLink();
        }
        return $cls;
    }

    /**
     * 查询数据库中所有表名
     * @return array|null
     */
    public function GetListByTableName(): ?array
    {
        $config = $this->db()->GetNowConfig();
        $list_table = $this->db()->SetSql([
            $this->GetSQLFile('mysql.table.show', 'db_name', $config['name'])
        ])->ToList();
        if (Arrays::Is($list_table)) {
            $list_table = Arrays::Column($list_table, 'Tables_in_' . strtolower($config['name']));
        }
        return $list_table;
    }

    public function GetEntityByTable(string $name_table): string
    {
        $entity = $this->db()->SetSql([
            $this->GetSQLFile('mysql.table.create', 'table_name', $name_table)
        ])->First();
        return <<<SQL
{$entity['Create Table']};
SQL;
    }

    public function GetListByData(string $name_table)
    {

        $sql_count = <<<SQL
SELECT COUNT(*) AS `count` FROM `{$name_table}`
SQL;
        $res_count = $this->db()->SetSql([$sql_count])->First();
        $this->count_rows = $res_count['count'];
        $max_rows = 100;
        if ($this->count_rows > $max_rows) {
            $list_sql = [];
            for ($i = 1; $i <= ceil($this->count_rows / $max_rows); $i++) {
                $list_sql[] = $this->_getList($name_table, $max_rows, $i);
            }
            return $list_sql;
        } else {
            return $this->_getList($name_table);
        }
    }

    private function _getList(string $name_table, int $rows = 100, int $index = 1): string
    {
        $index = ($index - 1) * $rows;
        $sql = <<<SQL
select * from `{$name_table}` limit {$index},{$rows}
SQL;
        $list = $this->db()->SetSql([$sql])->ToList();
        if (Arrays::Is($list)) {
            $this->db()->Insert($list, $name_table, true);
            $list_sql = ($this->db()->GetSql());
            return $list_sql[0];
        } else {
            return '';
        }
    }

    public function ExecSQL(string $str_sql)
    {
        $this->db()->BatchRun($str_sql);
    }

    public function DropTable(string $name_table, bool $is_exec = true)
    {
        $config = $this->db()->GetNowConfig();
        $this->db()->DropTable($config['name'], $name_table);
        !$is_exec ?: $this->db()->BatchRun();
    }

    public function interface_getEntityById($id, $viewField = '*')
    {
    }

    public function GetList($viewParams = [], $viewField = '*'): ?array
    {
    }

    public function GetEntity($viewParams = [], $viewField = '*')
    {
    }

    public function RemoveOfDataBaseByAll()
    {
        $list_table = $this->GetListByTableName();
        if ($count_table = Arrays::Is($list_table)) {
            foreach ($list_table as $index => $item) {
                $this->DropTable($item, ($index + 1) >= $count_table);
            }
        }
    }

}